<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="language" content="en" />
        <link href="./assets/ffd55088/css/bootstrap.css" rel="stylesheet">
<link href="./assets/5cf9384a/solarized_light.css" rel="stylesheet">
<link href="./assets/6c54116e/style.css" rel="stylesheet">
<script src="./assets/a44cef0f/jquery.js"></script>
<script src="./assets/ffd55088/js/bootstrap.js"></script>
<script src="./assets/8ac4e28a/jssearch.js"></script>    <title>Widgets - Application Structure - The Definitive Guide to Yii 2.0</title>
</head>
<body>

<div class="wrap">
    <nav id="w396" class="navbar-inverse navbar-fixed-top navbar" role="navigation"><div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#w396-collapse"><span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span></button><a class="navbar-brand" href="./index.html">The Definitive Guide to Yii 2.0</a></div><div id="w396-collapse" class="collapse navbar-collapse"><ul id="w397" class="navbar-nav nav"><li><a href="./index.html">Class reference</a></li>
<li class="dropdown"><a class="dropdown-toggle" href="#" data-toggle="dropdown">Extensions <b class="caret"></b></a><ul id="w398" class="dropdown-menu"><li><a href="./ext-apidoc-index.html" tabindex="-1">apidoc</a></li>
<li><a href="./ext-authclient-index.html" tabindex="-1">authclient</a></li>
<li><a href="./ext-bootstrap-index.html" tabindex="-1">bootstrap</a></li>
<li><a href="./ext-codeception-index.html" tabindex="-1">codeception</a></li>
<li><a href="./ext-debug-index.html" tabindex="-1">debug</a></li>
<li><a href="./ext-elasticsearch-index.html" tabindex="-1">elasticsearch</a></li>
<li><a href="./ext-faker-index.html" tabindex="-1">faker</a></li>
<li><a href="./ext-gii-index.html" tabindex="-1">gii</a></li>
<li><a href="./ext-imagine-index.html" tabindex="-1">imagine</a></li>
<li><a href="./ext-jui-index.html" tabindex="-1">jui</a></li>
<li><a href="./ext-mongodb-index.html" tabindex="-1">mongodb</a></li>
<li><a href="./ext-redis-index.html" tabindex="-1">redis</a></li>
<li><a href="./ext-smarty-index.html" tabindex="-1">smarty</a></li>
<li><a href="./ext-sphinx-index.html" tabindex="-1">sphinx</a></li>
<li><a href="./ext-swiftmailer-index.html" tabindex="-1">swiftmailer</a></li>
<li><a href="./ext-twig-index.html" tabindex="-1">twig</a></li></ul></li>
<li><a href="./guide-README.html">Guide</a></li></ul><div class="navbar-form navbar-left" role="search">
  <div class="form-group">
    <input id="searchbox" type="text" class="form-control" placeholder="Search">
  </div>
</div>
</div></nav>
    <div id="search-resultbox" style="display: none;" class="modal-content">
        <ul id="search-results">
        </ul>
    </div>

    
<div class="row">
    <div class="col-md-2">
                <div id="navigation" class="list-group"><a class="list-group-item" href="#navigation-380" data-toggle="collapse" data-parent="#navigation">Introduction <b class="caret"></b></a><div id="navigation-380" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-intro-yii.html">About Yii</a>
<a class="list-group-item" href="./guide-intro-upgrade-from-v1.html">Upgrading from Version 1.1</a></div>
<a class="list-group-item" href="#navigation-381" data-toggle="collapse" data-parent="#navigation">Getting Started <b class="caret"></b></a><div id="navigation-381" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-start-installation.html">Installing Yii</a>
<a class="list-group-item" href="./guide-start-workflow.html">Running Applications</a>
<a class="list-group-item" href="./guide-start-hello.html">Saying Hello</a>
<a class="list-group-item" href="./guide-start-forms.html">Working with Forms</a>
<a class="list-group-item" href="./guide-start-databases.html">Working with Databases</a>
<a class="list-group-item" href="./guide-start-gii.html">Generating Code with Gii</a>
<a class="list-group-item" href="./guide-start-looking-ahead.html">Looking Ahead</a></div>
<a class="list-group-item active" href="#navigation-382" data-toggle="collapse" data-parent="#navigation">Application Structure <b class="caret"></b></a><div id="navigation-382" class="submenu panel-collapse collapse in"><a class="list-group-item" href="./guide-structure-overview.html">Overview</a>
<a class="list-group-item" href="./guide-structure-entry-scripts.html">Entry Scripts</a>
<a class="list-group-item" href="./guide-structure-applications.html">Applications</a>
<a class="list-group-item" href="./guide-structure-application-components.html">Application Components</a>
<a class="list-group-item" href="./guide-structure-controllers.html">Controllers</a>
<a class="list-group-item" href="./guide-structure-models.html">Models</a>
<a class="list-group-item" href="./guide-structure-views.html">Views</a>
<a class="list-group-item" href="./guide-structure-modules.html">Modules</a>
<a class="list-group-item" href="./guide-structure-filters.html">Filters</a>
<a class="list-group-item active" href="./guide-structure-widgets.html">Widgets</a>
<a class="list-group-item" href="./guide-structure-assets.html">Assets</a>
<a class="list-group-item" href="./guide-structure-extensions.html">Extensions</a></div>
<a class="list-group-item" href="#navigation-383" data-toggle="collapse" data-parent="#navigation">Handling Requests <b class="caret"></b></a><div id="navigation-383" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-runtime-overview.html">Overview</a>
<a class="list-group-item" href="./guide-runtime-bootstrapping.html">Bootstrapping</a>
<a class="list-group-item" href="./guide-runtime-routing.html">Routing and URL Creation</a>
<a class="list-group-item" href="./guide-runtime-requests.html">Requests</a>
<a class="list-group-item" href="./guide-runtime-responses.html">Responses</a>
<a class="list-group-item" href="./guide-runtime-sessions-cookies.html">Sessions and Cookies</a>
<a class="list-group-item" href="./guide-runtime-handling-errors.html">Handling Errors</a>
<a class="list-group-item" href="./guide-runtime-logging.html">Logging</a></div>
<a class="list-group-item" href="#navigation-384" data-toggle="collapse" data-parent="#navigation">Key Concepts <b class="caret"></b></a><div id="navigation-384" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-concept-components.html">Components</a>
<a class="list-group-item" href="./guide-concept-properties.html">Properties</a>
<a class="list-group-item" href="./guide-concept-events.html">Events</a>
<a class="list-group-item" href="./guide-concept-behaviors.html">Behaviors</a>
<a class="list-group-item" href="./guide-concept-configurations.html">Configurations</a>
<a class="list-group-item" href="./guide-concept-aliases.html">Aliases</a>
<a class="list-group-item" href="./guide-concept-autoloading.html">Class Autoloading</a>
<a class="list-group-item" href="./guide-concept-service-locator.html">Service Locator</a>
<a class="list-group-item" href="./guide-concept-di-container.html">Dependency Injection Container</a></div>
<a class="list-group-item" href="#navigation-385" data-toggle="collapse" data-parent="#navigation">Working with Databases <b class="caret"></b></a><div id="navigation-385" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-db-dao.html">Data Access Objects</a>
<a class="list-group-item" href="./guide-db-query-builder.html">Query Builder</a>
<a class="list-group-item" href="./guide-db-active-record.html">Active Record</a>
<a class="list-group-item" href="./guide-db-migrations.html">Migrations</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-sphinx/blob/master/docs/guide/README.md">Sphinx</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-redis/blob/master/docs/guide/README.md">Redis</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-mongodb/blob/master/docs/guide/README.md">MongoDB</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/README.md">ElasticSearch</a></div>
<a class="list-group-item" href="#navigation-386" data-toggle="collapse" data-parent="#navigation">Getting Data from Users <b class="caret"></b></a><div id="navigation-386" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-input-forms.html">Creating Forms</a>
<a class="list-group-item" href="./guide-input-validation.html">Validating Input</a>
<a class="list-group-item" href="./guide-input-file-upload.html">Uploading Files</a>
<a class="list-group-item" href="./guide-input-tabular-input.html">Collecting Tabular Input</a>
<a class="list-group-item" href="./guide-input-multiple-models.html">Getting Data for Multiple Models</a></div>
<a class="list-group-item" href="#navigation-387" data-toggle="collapse" data-parent="#navigation">Displaying Data <b class="caret"></b></a><div id="navigation-387" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-output-formatting.html">Data Formatting</a>
<a class="list-group-item" href="./guide-output-pagination.html">Pagination</a>
<a class="list-group-item" href="./guide-output-sorting.html">Sorting</a>
<a class="list-group-item" href="./guide-output-data-providers.html">Data Providers</a>
<a class="list-group-item" href="./guide-output-data-widgets.html">Data Widgets</a>
<a class="list-group-item" href="./guide-output-client-scripts.html">Working with Client Scripts</a>
<a class="list-group-item" href="./guide-output-theming.html">Theming</a></div>
<a class="list-group-item" href="#navigation-388" data-toggle="collapse" data-parent="#navigation">Security <b class="caret"></b></a><div id="navigation-388" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-security-overview.html">Overview</a>
<a class="list-group-item" href="./guide-security-authentication.html">Authentication</a>
<a class="list-group-item" href="./guide-security-authorization.html">Authorization</a>
<a class="list-group-item" href="./guide-security-passwords.html">Working with Passwords</a>
<a class="list-group-item" href="./guide-security-cryptography.html">Cryptography</a>
<a class="list-group-item" href="./guide-structure-views.html#security">Views security</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-authclient/blob/master/docs/guide/README.md">Auth Clients</a>
<a class="list-group-item" href="./guide-security-best-practices.html">Best Practices</a></div>
<a class="list-group-item" href="#navigation-389" data-toggle="collapse" data-parent="#navigation">Caching <b class="caret"></b></a><div id="navigation-389" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-caching-overview.html">Overview</a>
<a class="list-group-item" href="./guide-caching-data.html">Data Caching</a>
<a class="list-group-item" href="./guide-caching-fragment.html">Fragment Caching</a>
<a class="list-group-item" href="./guide-caching-page.html">Page Caching</a>
<a class="list-group-item" href="./guide-caching-http.html">HTTP Caching</a></div>
<a class="list-group-item" href="#navigation-390" data-toggle="collapse" data-parent="#navigation">RESTful Web Services <b class="caret"></b></a><div id="navigation-390" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-rest-quick-start.html">Quick Start</a>
<a class="list-group-item" href="./guide-rest-resources.html">Resources</a>
<a class="list-group-item" href="./guide-rest-controllers.html">Controllers</a>
<a class="list-group-item" href="./guide-rest-routing.html">Routing</a>
<a class="list-group-item" href="./guide-rest-response-formatting.html">Response Formatting</a>
<a class="list-group-item" href="./guide-rest-authentication.html">Authentication</a>
<a class="list-group-item" href="./guide-rest-rate-limiting.html">Rate Limiting</a>
<a class="list-group-item" href="./guide-rest-versioning.html">Versioning</a>
<a class="list-group-item" href="./guide-rest-error-handling.html">Error Handling</a></div>
<a class="list-group-item" href="#navigation-391" data-toggle="collapse" data-parent="#navigation">Development Tools <b class="caret"></b></a><div id="navigation-391" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-debug/blob/master/docs/guide/README.md">Debug Toolbar and Debugger</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md">Generating Code using Gii</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-apidoc">Generating API Documentation</a></div>
<a class="list-group-item" href="#navigation-392" data-toggle="collapse" data-parent="#navigation">Testing <b class="caret"></b></a><div id="navigation-392" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-test-overview.html">Overview</a>
<a class="list-group-item" href="./guide-test-environment-setup.html">Testing environment setup</a>
<a class="list-group-item" href="./guide-test-unit.html">Unit Tests</a>
<a class="list-group-item" href="./guide-test-functional.html">Functional Tests</a>
<a class="list-group-item" href="./guide-test-acceptance.html">Acceptance Tests</a>
<a class="list-group-item" href="./guide-test-fixtures.html">Fixtures</a></div>
<a class="list-group-item" href="#navigation-393" data-toggle="collapse" data-parent="#navigation">Special Topics <b class="caret"></b></a><div id="navigation-393" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/README.md">Advanced Project Template</a>
<a class="list-group-item" href="./guide-tutorial-start-from-scratch.html">Building Application from Scratch</a>
<a class="list-group-item" href="./guide-tutorial-console.html">Console Commands</a>
<a class="list-group-item" href="./guide-tutorial-core-validators.html">Core Validators</a>
<a class="list-group-item" href="./guide-tutorial-i18n.html">Internationalization</a>
<a class="list-group-item" href="./guide-tutorial-mailing.html">Mailing</a>
<a class="list-group-item" href="./guide-tutorial-performance-tuning.html">Performance Tuning</a>
<a class="list-group-item" href="./guide-tutorial-shared-hosting.html">Shared Hosting Environment</a>
<a class="list-group-item" href="./guide-tutorial-template-engines.html">Template Engines</a>
<a class="list-group-item" href="./guide-tutorial-yii-integration.html">Working with Third-Party Code</a></div>
<a class="list-group-item" href="#navigation-394" data-toggle="collapse" data-parent="#navigation">Widgets <b class="caret"></b></a><div id="navigation-394" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-bootstrap/blob/master/docs/guide/README.md">Bootstrap Widgets</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-jui/blob/master/docs/guide/README.md">jQuery UI Widgets</a></div>
<a class="list-group-item" href="#navigation-395" data-toggle="collapse" data-parent="#navigation">Helpers <b class="caret"></b></a><div id="navigation-395" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-helper-overview.html">Overview</a>
<a class="list-group-item" href="./guide-helper-array.html">ArrayHelper</a>
<a class="list-group-item" href="./guide-helper-html.html">Html</a>
<a class="list-group-item" href="./guide-helper-url.html">Url</a></div></div>    </div>
    <div class="col-md-9 guide-content" role="main">
        <h1>Widgets <span id="widgets"></span><a href="#widgets" class="hashlink">&para;</a></h1>
<div class="toc"><ol><li><a href="#using-widgets">Using Widgets</a></li>
<li><a href="#creating-widgets">Creating Widgets</a></li>
<li><a href="#best-practices">Best Practices</a></li></ol></div>
<p>Widgets are reusable building blocks used in <a href="guide-structure-views.html">views</a> to create complex and configurable user
interface elements in an object-oriented fashion. For example, a date picker widget may generate a fancy date picker
that allows users to pick a date as their input. All you need to do is just to insert the code in a view
like the following:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">jui</span>\<span class="hljs-title">DatePicker</span>;
<span class="hljs-preprocessor">?&gt;</span>
<span class="hljs-preprocessor">&lt;?</span>= DatePicker::widget([<span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'date'</span>]) <span class="hljs-preprocessor">?&gt;</span>
</code></pre>
<p>There are a good number of widgets bundled with Yii, such as <a href="./yii-widgets-activeform.html">active form</a>,
<a href="./yii-widgets-menu.html">menu</a>, <a href="guide-widget-jui.html">jQuery UI widgets</a>, <a href="guide-widget-bootstrap.html">Twitter Bootstrap widgets</a>.
In the following, we will introduce the basic knowledge about widgets. Please refer to the class API documentation
if you want to learn about the usage of a particular widget.</p>
<h2>Using Widgets  <span id="using-widgets"></span><a href="#using-widgets" class="hashlink">&para;</a></h2><p>Widgets are primarily used in <a href="guide-structure-views.html">views</a>. You can call the <a href="./yii-base-widget.html#widget()-detail">yii\base\Widget::widget()</a> method
to use a widget in a view. The method takes a <a href="guide-concept-configurations.html">configuration</a> array for initializing
the widget and returns the rendering result of the widget. For example, the following code inserts a date picker
widget which is configured to use the Russian language and keep the input in the <code>from_date</code> attribute of <code>$model</code>.</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">jui</span>\<span class="hljs-title">DatePicker</span>;
<span class="hljs-preprocessor">?&gt;</span>
<span class="hljs-preprocessor">&lt;?</span>= DatePicker::widget([
    <span class="hljs-string">'model'</span> =&gt; <span class="hljs-variable">$model</span>,
    <span class="hljs-string">'attribute'</span> =&gt; <span class="hljs-string">'from_date'</span>,
    <span class="hljs-string">'language'</span> =&gt; <span class="hljs-string">'ru'</span>,
    <span class="hljs-string">'clientOptions'</span> =&gt; [
        <span class="hljs-string">'dateFormat'</span> =&gt; <span class="hljs-string">'yy-mm-dd'</span>,
    ],
]) <span class="hljs-preprocessor">?&gt;</span>
</code></pre>
<p>Some widgets can take a block of content which should be enclosed between the invocation of
<a href="./yii-base-widget.html#begin()-detail">yii\base\Widget::begin()</a> and <a href="./yii-base-widget.html#end()-detail">yii\base\Widget::end()</a>. For example, the following code uses the
<a href="./yii-widgets-activeform.html">yii\widgets\ActiveForm</a> widget to generate a login form. The widget will generate the opening and closing
<code>&lt;form&gt;</code> tags at the place where <code>begin()</code> and <code>end()</code> are called, respectively. Anything in between will be
rendered as is.</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">widgets</span>\<span class="hljs-title">ActiveForm</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">helpers</span>\<span class="hljs-title">Html</span>;
<span class="hljs-preprocessor">?&gt;</span>

<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-variable">$form</span> = ActiveForm::begin([<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'login-form'</span>]); <span class="hljs-preprocessor">?&gt;</span>

    <span class="hljs-preprocessor">&lt;?</span>= <span class="hljs-variable">$form</span>-&gt;field(<span class="hljs-variable">$model</span>, <span class="hljs-string">'username'</span>) <span class="hljs-preprocessor">?&gt;</span>

    <span class="hljs-preprocessor">&lt;?</span>= <span class="hljs-variable">$form</span>-&gt;field(<span class="hljs-variable">$model</span>, <span class="hljs-string">'password'</span>)-&gt;passwordInput() <span class="hljs-preprocessor">?&gt;</span>

    &lt;div <span class="hljs-class"><span class="hljs-keyword">class</span>="<span class="hljs-title">form</span>-<span class="hljs-title">group</span>"&gt;
        &lt;?= <span class="hljs-title">Html</span>::<span class="hljs-title">submitButton</span>('<span class="hljs-title">Login</span>') ?&gt;
    &lt;/<span class="hljs-title">div</span>&gt;

&lt;?<span class="hljs-title">php</span> <span class="hljs-title">ActiveForm</span>::<span class="hljs-title">end</span>(); ?&gt;
</span></code></pre>
<p>Note that unlike <a href="./yii-base-widget.html#widget()-detail">yii\base\Widget::widget()</a> which returns the rendering result of a widget, the method
<a href="./yii-base-widget.html#begin()-detail">yii\base\Widget::begin()</a> returns an instance of the widget which you can use to build the widget content.</p>
<blockquote class="note"><p><strong>Note: </strong>Some widgets will use <a href="http://php.net/manual/en/book.outcontrol.php">output buffering</a> to adjust the enclosed
content when <a href="./yii-base-widget.html#end()-detail">yii\base\Widget::end()</a> is called. For this reason calling <a href="./yii-base-widget.html#begin()-detail">yii\base\Widget::begin()</a> and
<a href="./yii-base-widget.html#end()-detail">yii\base\Widget::end()</a> is expected to happen in the same view file.
Not following this rule may result in unexpected output.</p>
</blockquote>
<h3>Configuring global defaults <span id="configuring-global-defaults"></span><a href="#configuring-global-defaults" class="hashlink">&para;</a></h3><p>Global defaults for a widget type could be configured via DI container:</p>
<pre><code class="hljs php language-php">\Yii::<span class="hljs-variable">$container</span>-&gt;set(<span class="hljs-string">'yii\widgets\LinkPager'</span>, [<span class="hljs-string">'maxButtonCount'</span> =&gt; <span class="hljs-number">5</span>]);
</code></pre>
<p>See <a href="guide-concept-di-container.html#practical-usage">"Practical Usage" section in Dependency Injection Container guide</a> for
details.</p>
<h2>Creating Widgets  <span id="creating-widgets"></span><a href="#creating-widgets" class="hashlink">&para;</a></h2><p>To create a widget, extend from <a href="./yii-base-widget.html">yii\base\Widget</a> and override the <a href="./yii-base-object.html#init()-detail">yii\base\Widget::init()</a> and/or
<a href="./yii-base-widget.html#run()-detail">yii\base\Widget::run()</a> methods. Usually, the <code>init()</code> method should contain the code that normalizes the widget
properties, while the <code>run()</code> method should contain the code that generates the rendering result of the widget.
The rendering result may be directly "echoed" or returned as a string by <code>run()</code>.</p>
<p>In the following example, <code>HelloWidget</code> HTML-encodes and displays the content assigned to its <code>message</code> property.
If the property is not set, it will display "Hello World" by default.</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">app</span>\<span class="hljs-title">components</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">base</span>\<span class="hljs-title">Widget</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">helpers</span>\<span class="hljs-title">Html</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HelloWidget</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Widget</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-variable">$message</span>;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">init</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-keyword">parent</span>::init();
        <span class="hljs-keyword">if</span> (<span class="hljs-variable">$this</span>-&gt;message === <span class="hljs-keyword">null</span>) {
            <span class="hljs-variable">$this</span>-&gt;message = <span class="hljs-string">'Hello World'</span>;
        }
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">run</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-keyword">return</span> Html::encode(<span class="hljs-variable">$this</span>-&gt;message);
    }
}
</code></pre>
<p>To use this widget, simply insert the following code in a view:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>
<span class="hljs-keyword">use</span> <span class="hljs-title">app</span>\<span class="hljs-title">components</span>\<span class="hljs-title">HelloWidget</span>;
<span class="hljs-preprocessor">?&gt;</span>
<span class="hljs-preprocessor">&lt;?</span>= HelloWidget::widget([<span class="hljs-string">'message'</span> =&gt; <span class="hljs-string">'Good morning'</span>]) <span class="hljs-preprocessor">?&gt;</span>
</code></pre>
<p>Below is a variant of <code>HelloWidget</code> which takes the content enclosed within the <code>begin()</code> and <code>end()</code> calls,
HTML-encodes it and then displays it.</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">app</span>\<span class="hljs-title">components</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">base</span>\<span class="hljs-title">Widget</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">helpers</span>\<span class="hljs-title">Html</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HelloWidget</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Widget</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">init</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-keyword">parent</span>::init();
        ob_start();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">run</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$content</span> = ob_get_clean();
        <span class="hljs-keyword">return</span> Html::encode(<span class="hljs-variable">$content</span>);
    }
}
</code></pre>
<p>As you can see, PHP's output buffer is started in <code>init()</code> so that any output between the calls of <code>init()</code> and <code>run()</code>
can be captured, processed and returned in <code>run()</code>.</p>
<blockquote class="info"><p><strong>Info: </strong>When you call <a href="./yii-base-widget.html#begin()-detail">yii\base\Widget::begin()</a>, a new instance of the widget will be created and the <code>init()</code> method
  will be called at the end of the widget constructor. When you call <a href="./yii-base-widget.html#end()-detail">yii\base\Widget::end()</a>, the <code>run()</code> method
  will be called whose return result will be echoed by <code>end()</code>.</p>
</blockquote>
<p>The following code shows how to use this new variant of <code>HelloWidget</code>:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>
<span class="hljs-keyword">use</span> <span class="hljs-title">app</span>\<span class="hljs-title">components</span>\<span class="hljs-title">HelloWidget</span>;
<span class="hljs-preprocessor">?&gt;</span>
<span class="hljs-preprocessor">&lt;?php</span> HelloWidget::begin(); <span class="hljs-preprocessor">?&gt;</span>

    content that may contain &lt;tag&gt;<span class="hljs-string">'s

&lt;?php HelloWidget::end(); ?&gt;
</span></code></pre>
<p>Sometimes, a widget may need to render a big chunk of content. While you can embed the content within the <code>run()</code>
method, a better approach is to put it in a <a href="guide-structure-views.html">view</a> and call <a href="./yii-base-widget.html#render()-detail">yii\base\Widget::render()</a> to
render it. For example,</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">run</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-variable">$this</span>-&gt;render(<span class="hljs-string">'hello'</span>);
}
</code></pre>
<p>By default, views for a widget should be stored in files in the <code>WidgetPath/views</code> directory, where <code>WidgetPath</code>
stands for the directory containing the widget class file. Therefore, the above example will render the view file
<code>@app/components/views/hello.php</code>, assuming the widget class is located under <code>@app/components</code>. You may override
the <a href="./yii-base-widget.html#getViewPath()-detail">yii\base\Widget::getViewPath()</a> method to customize the directory containing the widget view files.</p>
<h2>Best Practices  <span id="best-practices"></span><a href="#best-practices" class="hashlink">&para;</a></h2><p>Widgets are an object-oriented way of reusing view code.</p>
<p>When creating widgets, you should still follow the MVC pattern. In general, you should keep logic in widget
classes and keep presentation in <a href="guide-structure-views.html">views</a>.</p>
<p>Widgets should be designed to be self-contained. That is, when using a widget, you should be able to just drop
it in a view without doing anything else. This could be tricky if a widget requires external resources, such as
CSS, JavaScript, images, etc. Fortunately, Yii provides the support for <a href="guide-structure-assets.html">asset bundles</a>,
which can be utilized to solve the problem.</p>
<p>When a widget contains view code only, it is very similar to a <a href="guide-structure-views.html">view</a>. In fact, in this case,
their only difference is that a widget is a redistributable class, while a view is just a plain PHP script
that you would prefer to keep within your application.</p>
        <div class="toplink"><a href="#" class="h1" title="go to top"><span class="glyphicon glyphicon-arrow-up"></a></div>
    </div>
</div>


</div>

<footer class="footer">
        <p class="pull-right"><small>Page generated on Sat, 09 Jul 2016 12:16:28 +0000</small></p>
    Powered by <a href="http://www.yiiframework.com/" rel="external">Yii Framework</a></footer>

<script type="text/javascript">jQuery(document).ready(function () {
    var shiftWindow = function () { scrollBy(0, -50) };
    if (location.hash) setTimeout(shiftWindow, 1);
    window.addEventListener("hashchange", shiftWindow);
var element = document.createElement("script");
element.src = "./jssearch.index.js";
document.body.appendChild(element);

var searchBox = $('#searchbox');

// search when typing in search field
searchBox.on("keyup", function(event) {
    var query = $(this).val();

    if (query == '' || event.which == 27) {
        $('#search-resultbox').hide();
        return;
    } else if (event.which == 13) {
        var selectedLink = $('#search-resultbox a.selected');
        if (selectedLink.length != 0) {
            document.location = selectedLink.attr('href');
            return;
        }
    } else if (event.which == 38 || event.which == 40) {
        $('#search-resultbox').show();

        var selected = $('#search-resultbox a.selected');
        if (selected.length == 0) {
            $('#search-results').find('a').first().addClass('selected');
        } else {
            var next;
            if (event.which == 40) {
                next = selected.parent().next().find('a').first();
            } else {
                next = selected.parent().prev().find('a').first();
            }
            if (next.length != 0) {
                var resultbox = $('#search-results');
                var position = next.position();

//              TODO scrolling is buggy and jumps around
//                resultbox.scrollTop(Math.floor(position.top));
//                console.log(position.top);

                selected.removeClass('selected');
                next.addClass('selected');
            }
        }

        return;
    }
    $('#search-resultbox').show();
    $('#search-results').html('<li><span class="no-results">No results</span></li>');

    var result = jssearch.search(query);

    if (result.length > 0) {
        var i = 0;
        var resHtml = '';

        for (var key in result) {
            if (i++ > 20) {
                break;
            }
            resHtml = resHtml +
            '<li><a href="' + result[key].file.u.substr(3) +'"><span class="title">' + result[key].file.t + '</span>' +
            '<span class="description">' + result[key].file.d + '</span></a></li>';
        }
        $('#search-results').html(resHtml);
    }
});

// hide the search results on ESC
$(document).on("keyup", function(event) { if (event.which == 27) { $('#search-resultbox').hide(); } });
// hide search results on click to document
$(document).bind('click', function (e) { $('#search-resultbox').hide(); });
// except the following:
searchBox.bind('click', function(e) { e.stopPropagation(); });
$('#search-resultbox').bind('click', function(e) { e.stopPropagation(); });

});</script></body>
</html>
